package com.exercise.ThreadSynchronization.volatileMethod;

public class VolatileFlagDemo {
    // 使用volatile修饰状态标志
    private volatile boolean running = true;

    public void startTask(){
        new Thread(()->{
            while(running){
                System.out.println("Thread is running");
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            System.out.println("Thread stopped");
        }).start();
    }

    public void stopTask(){
        running = false;
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileFlagDemo demo = new VolatileFlagDemo();
        demo.startTask();
        //运行3秒
        Thread.sleep(3000);
        demo.stopTask();

    }
}
